# -*- coding: utf-8 -*-
"""
User authentication models for the Django backend application.
"""
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone
from datetime import timedelta
import secrets


class User(AbstractUser):
    """
    Custom User model extending AbstractUser with email authentication.
    
    This model uses email as the primary authentication field instead of username,
    and includes additional fields for email verification and timestamps.
    """
    email = models.EmailField(unique=True, help_text="User's email address (used for authentication)")
    is_email_verified = models.BooleanField(
        default=False, 
        help_text="Whether the user's email address has been verified"
    )
    created_at = models.DateTimeField(auto_now_add=True, help_text="When the user account was created")
    updated_at = models.DateTimeField(auto_now=True, help_text="When the user account was last updated")

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    class Meta:
        db_table = 'accounts_user'
        verbose_name = 'User'
        verbose_name_plural = 'Users'

    def __str__(self):
        return self.email


class PasswordResetToken(models.Model):
    """
    Model for secure password reset tokens.
    
    This model stores tokens used for password reset functionality with
    expiration times and usage tracking for security.
    """
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE,
        help_text="User this reset token belongs to"
    )
    token = models.CharField(
        max_length=100, 
        unique=True,
        help_text="Secure token for password reset"
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="When the token was created"
    )
    expires_at = models.DateTimeField(
        help_text="When the token expires"
    )
    is_used = models.BooleanField(
        default=False,
        help_text="Whether the token has been used"
    )

    class Meta:
        db_table = 'accounts_password_reset_token'
        verbose_name = 'Password Reset Token'
        verbose_name_plural = 'Password Reset Tokens'
        ordering = ['-created_at']

    def __str__(self):
        return f"Password reset token for {self.user.email}"

    def save(self, *args, **kwargs):
        """Override save to set expiration time and generate token if needed."""
        if not self.token:
            self.token = secrets.token_urlsafe(32)
        if not self.expires_at:
            self.expires_at = timezone.now() + timedelta(hours=1)
        super().save(*args, **kwargs)

    def is_expired(self):
        """Check if the token has expired."""
        return timezone.now() > self.expires_at

    def is_valid(self):
        """Check if the token is valid (not used and not expired)."""
        return not self.is_used and not self.is_expired()
